package com.tianji.learning.mq;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.mapper.LearningLessonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/*
 *   Description LessonDeleteListener
 *   @author zhangyan
 *   @time   2024/12/7
 */
@Component
@Slf4j
public class LessonDeleteListener {
    @Autowired
    private LearningLessonMapper learningLessonMapper;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "lessoning.delete.queue", durable = "true"),
                    exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE, type = "topic"),
                    key = MqConstants.Key.ORDER_REFUND_KEY
            )
    )
    public void handleLessonDelete(OrderBasicDTO dto){
        log.info("删除课程表，课程id为：{}", dto.getCourseIds());
        //todo 删除退款成功的课程
        List<Long> courseIds = dto.getCourseIds();
        if (courseIds.isEmpty()){
            return;
        }
        LambdaQueryWrapper<LearningLesson> wrapper = Wrappers.lambdaQuery(LearningLesson.class);
        wrapper.eq(LearningLesson::getUserId, dto.getUserId());
        for (Long courseId : courseIds) {
            wrapper.eq(LearningLesson::getCourseId, courseId);
            int delete = learningLessonMapper.delete(wrapper);
            if (delete < 1){
                log.error("删除课程表失败，课程id为：{}", courseId);
            }
        }
    }
}
